package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysMember;
import com.ruoyi.common.utils.CovertUtil;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UnzipAndListFilesUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.response.TopicDoc;
import com.ruoyi.system.service.ISysDocService;
import com.ruoyi.system.service.ISysTopicTypeService;
import com.ruoyi.web.controller.demo.domain.topicModel;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ISysTopicService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2024-10-26
 */
@Controller
@RequestMapping("/system/topic")
public class SysTopicController extends BaseController
{
    private String prefix = "system/topic";

    @Autowired
    private ISysTopicService sysTopicService;
    @Autowired
    private ISysDocService iSysDocService;
    @Autowired
    private ISysTopicTypeService iSysTopicTypeService;
    @Autowired
    private ServerConfig serverConfig;
    @RequiresPermissions("system:topic:view")
    @GetMapping()
    public String topic()
    {
        return prefix + "/topic";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:topic:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysTopic sysTopic)
    {
        startPage();
        List<SysTopic> list = sysTopicService.selectTopicByUserid(0l);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setTopsize(FileUtils.convertFileSizeToString(list.get(i).getSize()));
            list.get(i).setCover(serverConfig.getUrl() + list.get(i).getCover());
        }

        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:topic:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysTopic sysTopic)
    {
        List<SysTopic> list = sysTopicService.selectSysTopicList(sysTopic);
        ExcelUtil<SysTopic> util = new ExcelUtil<SysTopic>(SysTopic.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:topic:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysTopic sysTopic)
    {
        return toAjax(sysTopicService.insertSysTopic(sysTopic));
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("system:topic:edit")
    @GetMapping("/edit/{topicid}")
    public String edit(@PathVariable("topicid") Long topicid, ModelMap mmap)
    {
        SysTopic sysTopic = sysTopicService.selectSysTopicByTopicid(topicid);
        mmap.put("sysTopic", sysTopic);
        List<SysTopicType> sysTopicTypeList = iSysTopicTypeService.selectSysTopicTypeList(new SysTopicType());
        mmap.put("topic_type_array",sysTopicTypeList);
        List<String> listdocids = Arrays.asList(sysTopic.getDocs().split(","));
        List<SysDoc> sysDocList = iSysDocService.selectByDocIds(listdocids);
        List<topicModel> topModels = new ArrayList<>();
        for (int i=0;i<sysDocList.size();i++)
        {
            topicModel topicmodel = new topicModel();
            topicmodel.setId(sysDocList.get(i).getDocid());
            topicmodel.setName(sysDocList.get(i).getTitle());
            topModels.add(topicmodel);
        }
        mmap.put("docs", JSONObject.toJSONString(topModels));
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:topic:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysTopic sysTopic)
    {
        if(!sysTopic.getDocs().isEmpty()) {
            List<String> listdocids = Arrays.asList(sysTopic.getDocs().split(","));
            TopicDoc topicDoc = iSysDocService.selectByIdsSel(listdocids);
            sysTopic.setSize(topicDoc.getSize().longValue());
        }

        return toAjax(sysTopicService.updateSysTopic(sysTopic));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:topic:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sysTopicService.deleteSysTopicByTopicids(ids));
    }
    @RequiresPermissions("system:topic:edit")
    @GetMapping("/doc")
    public String doc(@RequestParam("docs") String docs, ModelMap mmap)
    {
        mmap.put("docs",docs);
        return prefix + "/doc";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:topic:edit")
    @PostMapping("/listdoc")
    @ResponseBody
    public TableDataInfo list(SysDoc sysDoc) {
        List<String> listdocids = new ArrayList<>();
        if(!StringUtils.isEmpty(sysDoc.getDocs()))
            listdocids = Arrays.asList(sysDoc.getDocs().split(","));
        startPage();
        List<SysDoc> list = iSysDocService.selectSysDocList1(sysDoc);
        for (int i = 0; i < list.size(); i++) {
            if (listdocids.contains(String.valueOf(list.get(i).getDocid())))
                list.get(i).setCheck(true);
            else
                list.get(i).setCheck(false);
            list.get(i).setPcount((long) CovertUtil.countFilesWithExtension(new File(StringUtils.getdir(list.get(i).getPath())), ".view"));
            list.get(i).setDocsize(FileUtils.convertFileSizeToString(list.get(i).getSize()));
            if (StringUtils.localFile(list.get(i).getPath()))
                list.get(i).setPath(serverConfig.getUrl() + StringUtils.localpng(list.get(i).getPath()));
        }
        return getDataTable(list);
    }
    //下载
    @GetMapping(value = {"/downtopic.htm"})
    public ResponseEntity<ByteArrayResource> downtopic(@RequestParam("topicid") long topicid) throws IOException {
        SysTopic sysTopic = sysTopicService.selectSysTopicByTopicid(topicid);
        List<String> listdocids = Arrays.asList(sysTopic.getDocs().split(","));
        List<SysDoc> sysDocList = iSysDocService.selectByDocIds(listdocids);
        List<ParamUpload> paramDocList = new ArrayList<>();
        for(int i=0;i<sysDocList.size();i++) {
            ParamUpload paramDoc = new ParamUpload();
            String docpath = sysDocList.get(i).getPath();
            String pre = Constants.RESOURCE_PREFIX;
            String dirname = RuoYiConfig.getProfile();
            String srcurl = dirname + docpath.replace(pre, "");
            String sorcename = sysDocList.get(i).getTitle() + "." + sysDocList.get(i).getExten();
            if(StringUtils.rename(paramDocList,sorcename))
                sorcename = sysDocList.get(i).getTitle()+"("+ IdUtils.randomUUID()+")."+sysDocList.get(i).getExten();
            paramDoc.setPath(srcurl);
            paramDoc.setTitle(sorcename);
            paramDocList.add(paramDoc);
        }
        String topfilename = sysTopic.getTitle()+".zip";
        String zipfile = RuoYiConfig.getDownloadPath()+sysTopic.getTitle()+".zip";
        UnzipAndListFilesUtils.zipFiles(zipfile,paramDocList);
        byte[] bytes = Files.readAllBytes(new File(zipfile).toPath());

        ByteArrayResource bar = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=\"" + URLEncoder.encode(topfilename) + "\";charset=utf-8")
                .body(bar);
    }
}
